<template>
  <div id="viewDiv2"></div>
</template>

<script>
import { EsriNameSpace } from '../../api/arcgis/esri-namespace'

export default {
  naem: 'qhh-heatmap',
  data() {
    return {
      EsriNameSpace: new EsriNameSpace(),
    }
  },
  mounted() {
    this.EsriNameSpace.initNameSpace().then(() => {
      const pt = this.EsriNameSpace.Point({
        x: 119.033957,
        y: 31.688996,
        spatialReference: 4490,
      })
      this.initMap(pt, 2)
      this.getJsonData(this.EsriNameSpace, this.ZGMap)
    })
    this.$bus.$on('oneMap', (res) => {
      if (res.type === 'dem') {
        return
      } else {
        this.ZGMapView.extent = res.extent
      }
    })
  },
  methods: {
    // 初始化地图
    initMap(center, zoom) {
      console.log('初始化地图--ING')
      const layerNew = new this.EsriNameSpace.TileLayer({
        url:
          'http://218.94.6.92:6080/arcgis/rest/services/jspub_raster_L4_L20/MapServer',
        // spatialReference: new this.EsriNameSpace.SpatialReference({
        //   wkid: 4490,
        // }),
        // visible: false,
      })
      this.ZGMap = new this.EsriNameSpace.Map({
        // basemap: 'topo',
        // basemap: {
        //   baseLayers: [layerNew],
        // },
        // layers: [layerNew],
      })
      this.ZGMapView = new this.EsriNameSpace.MapView({
        map: this.ZGMap, // 地图类型样式
        container: 'viewDiv2', // 地图容器
        center: [121.049, 30.485],
        zoom: 5,
        popup: {
          dockEnabled: true,
          autoOpenEnabled: false,
          dockOptions: {
            buttonEnabled: false,
          },
        },
      })
      this.ZGMapView.ui.remove('zoom')
    }, // initMap End

    /**
     * 添加热力图的geometry
     * EsriNameSpace ：自定义的esri API内所需的类对象
     * geometry ：通过数据创建的geometry
     * Layer ：需要添加geometry的图层
     * attributes ：图层的属性值（需要包含热力图渲染的字段名称，和fields、field对应【如：num】）
     */
    addFeature(EsriNameSpace, geometry, Layer, attributes) {
      const addFeature = EsriNameSpace.Graphic({
        geometry: geometry,
        attributes: attributes,
      })
      Layer.applyEdits({
        addFeatures: [addFeature],
      })
    },
    /**
     * 创建热力图图层
     * EsriNameSpace ：自定义的esri API内所需的类对象
     * layerVisible ：图层的可见性（true/false）
     */
    createHeatMapFeatureLayer(EsriNameSpace, layerVisible) {
      return new EsriNameSpace.FeatureLayer({
        objectIdField: 'ObjectID',
        source: [],
        outFields: '*',
        geometryType: 'point',
        visible: layerVisible,
        copyright: 'ZG',
        title: 'HeatMap',
        id: 'HeatMap',
        fields: [
          {
            alias: 'name',
            name: 'name',
            type: 'string',
          },
          {
            alias: 'zvalue',
            name: 'zvalue',
            type: 'oid',
          },
        ],
        renderer: {
          type: 'heatmap',
          field: 'zvalue',
          blurRadius: 20,
          colorStops: [
            { ratio: 0, color: 'rgba(0, 126, 255, 0)' },
            { ratio: 0.3, color: '#38C500' },
            { ratio: 0.5, color: '#FCFF00' },
            { ratio: 0.8, color: '#FF6C00' },
            { ratio: 1, color: '#FF0000' },
          ],
          minPixelIntensity: 0,
          maxPixelIntensity: 200,
        },
      })
    },

    createHeatMapTextLayer(EsriNameSpace) {
      return new EsriNameSpace.GraphicsLayer({
        id: 'text',
        opacity: 0,
      })
    },

    // 获取json数据，添加热力图数据
    getJsonData(EsriNameSpace, map) {
      this.$axios
        .get('http://mock-api.com/6KLe9xzk.mock/qhh')
        .then((response) => {
          console.log(response)
          // 创建图层
          const heatMapFeatureLayer = this.createHeatMapFeatureLayer(
            EsriNameSpace,
            true
          )

          // 创建图层
          const heatMapTextLayer = this.createHeatMapTextLayer(EsriNameSpace)

          const pointData = response.data.DATA.wm //dem
          // 遍历json,创建geometry，并添加到heatMapFeatureLayer里面
          pointData.forEach((item, index) => {
            const pointItem = {
              type: 'point',
              latitude: item.lat,
              longitude: item.lng,
            }
            this.addFeature(EsriNameSpace, pointItem, heatMapFeatureLayer, {
              zvalue: item.zvalue,
              index,
            })

            // 添加新图层，展示信息框
            this.createPointGraphics(
              item,
              EsriNameSpace,
              heatMapTextLayer,
              index
            )
          })

          // 添加图层到map
          map.addMany([heatMapFeatureLayer, heatMapTextLayer])
        })
    },

    // 通过ZOOM改变，修改热力图的影响的范围
    changeSize(zoom, size) {
      const sizeNum = zoom * size
      return {
        type: 'heatmap',
        field: 'zvalue',
        blurRadius: sizeNum,
        colorStops: [
          { ratio: 0.1, color: 'rgba(0, 126, 255, 0)' },
          { ratio: 0.2, color: '#614EFD' },
          { ratio: 0.3, color: '#44C0E5' },
          { ratio: 0.4, color: '#59DBD0' },
          { ratio: 0.5, color: '#BBF39F' },
          { ratio: 0.6, color: '#D2E590' },
          { ratio: 0.7, color: '#FFA965' },
          { ratio: 0.8, color: '#FF5F3C' },
          { ratio: 1, color: '#FF201C' },
        ],
        minPixelIntensity: 0,
        maxPixelIntensity: 200,
      }
    },

    createPointGraphics(item, EsriNameSpace, heatMapTextLayer, index) {
      // const pointSymbolNormal = {
      //   type: 'picture-marker',
      //   url: require('../assets/imgs/gps.svg'),
      //   width: '34px',
      //   height: '42px',
      //   xoffset: '0px',
      //   yoffset: '0px',
      // }
      const pointX = item.lng
      const pointY = item.lat

      const point = {
        type: 'point',
        latitude: pointY,
        longitude: pointX,
      }

      const pointGraphic = new EsriNameSpace.Graphic({
        geometry: point,
        attributes: {
          zvalue: item.zvalue,
          index,
        },
        popupTemplate: {
          outFields: '*',
          title: '{zvalue}和{index}',
        },
        // symbol: pointSymbolNormal,
      })
      heatMapTextLayer.graphics.add(pointGraphic)
    },

    showPopup(topResult, mapView) {
      mapView.popup.actions.removeAll()
      // this.closePopup(mapView)
      console.log('99')
      mapView.popup.open({
        // title: 'dfghjk', // graphic[0].graphic.attributes.name,
        location: topResult.mapPoint,
        content:
          "<div style='width: 100%;overflow: hidden;height: 100%;margin-top: 13px;'>" +
          "<p style='margin: 5px 0;font-size: 14px;color: #333333;'><b>" +
          '999999999999999999999999999999' +
          '</b></p>' +
          '</div>',
      })
    },

    closePopup(mapView) {
      //  内容为空，内容不是 指定图层，关闭信息框
      mapView.popup.close()
      // document.body.style.cursor = 'default'
    },
  },
}
</script>

<style scoped>
#viewDiv2 {
  width: 100vw;
  height: 100vh;
}
</style>
